﻿using System;
using System.Collections.Generic;
using UnityEngine;




public static class StringTools
{
    // 一个特定的字符串解析功能
    //public static class StringPool
    //{

    //    public static Dictionary<string, string> stringPool = new Dictionary<string, string>();

    //    public static string GetTureKeyFromPool(string key)
    //    {
    //        if (stringPool.ContainsKey(key))
    //        {
    //            return stringPool[key];
    //        }
    //        else
    //        {
    //            string strParam = null;
    //            if (key.Contains("#")) // 如果有#好，就是从表里读数据
    //            {
    //                strParam = key.Replace("#", "");
    //                stringPool.Add(key, strParam);
    //            }
    //            else if (key.Contains("$")) // 如果有$好，就是从公式表里算
    //            {
    //                strParam = key.Replace("$", "");
    //            }
    //            return strParam;
    //        }
    //    }
    //} 

    /// <summary>
    /// 数字转字符串，Lua的数字转字符串会保留小数点后面的0，C#的不会。
    /// </summary>
    /// <param name="num">数字。</param>
    /// <param name="w">固定最小宽度。</param>
    /// <returns>字符串。</returns>
    public static string NumberToString(double num, int w = 0)
    {
        string str = num.ToString();
        if (str.Length >= w)
        {
            return str;
        }
        return new string(' ', w - str.Length) + str;
    }
    /// <summary>
    /// long转string
    /// </summary>
    /// <param name="str">输入字符串</param>
    /// <param name="valueDefault">如果没有数字，返回的默认值</param>
    /// <returns></returns>
    public static long StringToLong(string str, long valueDefault = -1)
    {
        long value;
        if (!long.TryParse(str, out value))
            return valueDefault;
        if (value < long.MinValue || value > long.MaxValue)
            return valueDefault;
        return value;
    }

    /// <summary>
    /// 将字符串以 特定字符 为间隔分解成字符串列表
    /// </summary>
    /// <param name="strParam">输入字符串</param>
    /// <param name="splitParam">间隔的字符</param>
    /// <returns></returns>
    public static List<string> GetStringList(string strParam, char splitParam = ',')
    {
        List<string> strList = new List<string>();
        if (string.IsNullOrEmpty(strParam))
            return strList;
        string[] nodeNames = strParam.Split(splitParam);
        foreach (var idStr in nodeNames)
        {
            string str = idStr.Trim();
            if (string.IsNullOrEmpty(str))
                continue;
            strList.Add(str);
        }
        return strList;
    }
    //  读取csv格式的字符串
    public static List<string> GetStringListWithSpace(string strParam, char splitParam = ',')
    {

        List<string> strList = new List<string>();
        if (string.IsNullOrEmpty(strParam))
            return strList;

        string strKey = ",\"";  // 字符串开始
        string strKey2 = "\","; // 字符串结束
        if (strParam.IndexOf(strKey) > 0) // 如果有 引号，就要走引号处理流程
        {
            int nLast = 0;
            int index = strParam.IndexOf(",");
            while (index <= strParam.Length && index > 0)
            {
                var key = strParam.Substring(nLast, index - nLast);
                key = key.Replace("\"", "");
                strList.Add(key);
                // 如果下一个字符是引号，就找下一个引号s
                if (index < strParam.Length - 1 && strParam[index + 1] == '\"')
                {
                    nLast = index + 1;
                    index = strParam.IndexOf(strKey2, nLast) + 1; // 这里一定会找到
                }
                else
                {
                    nLast = index + 1;
                    index = strParam.IndexOf(",", nLast);
                }
            }

        }
        else
        {
            string[] nodes = strParam.Split(splitParam);
            strList = new List<string>(nodes);
        }

        return strList;
    }
    // 处理带小数的字符串
    /// <summary>
    /// 将字符串转换为浮点列表，以逗号间隔
    /// </summary>
    /// <param name="strParam"></param>
    /// <returns></returns>
    public static List<double> GetDoubleList(string strParam, char splitParam = ',')
    {
        List<double> idList = new List<double>();
        if (strParam == null)
            return idList;
        if (strParam == "")
            return idList;
        RemoveBrackets(ref strParam);
        string[] nodeNames = SplitString(strParam, splitParam);
        foreach (var idStr in nodeNames)
        {
            if (string.IsNullOrEmpty(idStr) == false)
            {
                double id;
                if (double.TryParse(idStr, out id))
                    idList.Add(id);
                else
                    throw new Exception("Failed to parse id: " + idStr);
            }
        }
        return idList;
    }

    public static List<float> GetFloatList(string strParam, char splitParam = ',')
    {
        List<float> idList = new List<float>();
        if (strParam == null)
            return idList;
        if (strParam == "")
            return idList;
        RemoveBrackets(ref strParam);
        string[] nodeNames = SplitString(strParam, splitParam);
        foreach (var idStr in nodeNames)
        {
            if (string.IsNullOrEmpty(idStr) == false)
            {
                float id;
                if (float.TryParse(idStr, out id))
                    idList.Add(id);
                else
                    throw new Exception("Failed to parse id: " + idStr);
            }
        }
        return idList;
    }

    /// <summary>
    ///  将字符串转换为long列表，以逗号间隔
    /// </summary>
    /// <param name="strParam"></param>
    /// <returns></returns>
    public static List<long> GetLongList(string strParam, char splitParam = ',')
    {
        List<long> idList = new List<long>();
        if (strParam == null)
            return idList;
        if (strParam == "")
            return idList;
        RemoveBrackets(ref strParam);
        string[] nodeNames = SplitString(strParam, splitParam);
        foreach (var idStr in nodeNames)
        {
            long id;
            try
            {
                id = long.Parse(idStr);
                idList.Add(id);
            }
            catch (Exception)
            {
                // ignore
            }
        }
        return idList;
    }
    /// <summary>
    /// 将字符串转换为int列表，以逗号间隔
    /// </summary>
    /// <param name="strParam"></param>
    /// <returns></returns>
    // Convert a string to a list of integers
    // The string is in the format [x,y,z] where x, y, z are integers
    // For example the string [1,2,3] will return the list of integers {1,2,3}
    public static List<int> GetIntList(string strParam, char splitParam = ',')
    {
        // Create a new list of integers
        List<int> idList = new List<int>();
        // If the string is null then return an empty list
        if (strParam == null)
            return idList;
        // Remove any brackets from the string
        RemoveBrackets(ref strParam);
        // Split the string into a list of strings using the comma as the separator
        string[] nodeNames = SplitString(strParam, splitParam);
        // Loop through each string in the list
        foreach (var idStr in nodeNames)
        {
            // Convert the string to an integer
            int id;
            if (int.TryParse(idStr, out id))
                // If the conversion succeeded then add the integer to the list
                idList.Add(id);
        }
        // Return the list of integers
        return idList;
    }
    public static List<T> StringToList<T>(string str)
    {
        List<T> list = new List<T>();
        string[] value = SplitString(str);
        for (int i = 0; i < value.Length; i++)
        {
            list.Add((T)Convert.ChangeType(value[i], typeof(T)));
        }
        return list;
    }
    //根据,将字符串转为字符串数组
    public static string[] SplitString(string str, char splitParam = ',')
    {
        return str.Split(splitParam);
    }
    // 去掉字符串里的 [ ] 符号
    public static void RemoveBrackets(ref string strParam)
    {
        strParam = strParam.Replace("[", "");
        strParam = strParam.Replace("]", "");
    }

    public static string ListToString(int[] list, int num = -1)
    {
        string str = "";
        if (num < 0)
            num = list.Length;
        for (int i = 0; i < num; i++)
        {
            str += list[i].ToString();
            if (i < num - 1)
                str += ",";
        }
        return str;
    }

    /// <summary>
    ///  获取字符串里小数点后的数字   0.1123 =>  1123
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static int GetIntFromString(string str)
    {
        var index = str.IndexOf(".");
        if (index > 0)
            str = str.Substring(0, index);
        else if (index == 0)
            str = "0";
        return int.Parse(str);
    }
    /// <summary>
    /// 获取字符串里 指定 strKey = 的数值
    /// 支持以 | 为间隔的多组字符对应
    /// </summary>
    /// <param name="str"></param>
    /// <param name="strKey"></param>
    /// <param name="def"></param>
    /// <returns></returns>
    static string GetValueFromString(string str, string strKey, string def = "")
    {
        if (String.IsNullOrEmpty(str))
            return def;
        if (str == "-1")
            return def;
        string[] nodeNames = str.Split('|');
        string[] data = nodeNames[0].Split('=');
        for (int i = 0; i < nodeNames.Length; ++i)
        {
            data = nodeNames[i].Split('=');
            if (data.Length == 2)
            {
                if (data[0] == strKey) // 过滤掉type
                    return data[1];
            }
        }
        return def;
    }
    /// <summary>
    /// 获取字符串字典的int值
    /// </summary>
    /// <param name="str"></param>
    /// <param name="strKey"></param>
    /// <param name="def">默认值</param>
    /// <returns></returns>
    public static int GetIntFromString(string str, string strKey, int def = 0)
    {
        string value = GetValueFromString(str, strKey, def.ToString());
        return int.Parse(value);
    }
    /// <summary>
    /// 获取字符串字典的float值
    /// </summary>
    /// <param name="str"></param>
    /// <param name="strKey"></param>
    /// <param name="fDefault"></param>
    /// <returns></returns>
    public static float GetFloatFromString(string str, string strKey, float fDefault = 0)
    {
        string value = GetValueFromString(str, strKey, fDefault.ToString());
        return float.Parse(value);

    }
    ///// <summary>
    ///// 获取字符串字典的int列表    
    ///// </summary>
    ///// <param name="str"></param>
    ///// <param name="idList"></param>
    public static void GetIntListFromString(string str, List<int> idList)
    {
        if (string.IsNullOrEmpty(str))
            return;
        if (str == "-1")
            return;
        string[] nodeNames = str.Split('|');
        int type = 0;
        string[] data = nodeNames[0].Split('=');
        for (int i = 0; i < nodeNames.Length; ++i)
        {
            data = nodeNames[i].Split('=');
            if (data.Length == 2)
            {
                if (int.TryParse(data[0], out type)) // 如果类型是数字
                    idList.Add(int.Parse(data[1]));
            }
        }
    }



    public static void GetLongListFromString(string str, List<long> idList)
    {
        if (str == null)
            return;
        if (str == "")
            return;
        if (str == "-1")
            return;
        string[] nodeNames = str.Split('|');

        string[] data = nodeNames[0].Split('=');
        for (int i = 0; i < nodeNames.Length; ++i)
        {
            data = nodeNames[i].Split('=');
            if (data.Length == 2)
            {
                if (System.Text.RegularExpressions.Regex.IsMatch(data[0], @"^\d{1}$")) // 如果类型是数字
                    idList.Add(long.Parse(data[1]));
            }
        }
    }
    public static List<string> GetStringListCheckNull(string strParam, char splitParam = ',')
    {
        if (string.IsNullOrEmpty(strParam))
            return null;
        return GetStringList(strParam, splitParam);
    }

    public static Dictionary<int, int> TranslateStringToIntDic(string str)
    {
        Dictionary<int, int> strDic = new Dictionary<int, int>();
        string[] nodeNames = str.Split('|');
        for (int i = 0; i < nodeNames.Length; ++i)
        {
            string[] data = nodeNames[i].Split('=');
            if (data.Length == 2)
                strDic.Add(int.Parse(data[0]), int.Parse(data[1]));
        }
        return strDic;
    }

    public static Dictionary<string, string> TranslateStringToDic(string str)
    {
        Dictionary<string, string> strDic = new Dictionary<string, string>();
        string[] nodeNames = str.Split('|');
        for (int i = 0; i < nodeNames.Length; ++i)
        {
            string[] data = nodeNames[i].Split('=');
            if (data.Length == 2)
                strDic.Add(data[0], data[1]);
        }
        return strDic;
    }
    //public static void TranslateStringToLongList(string str, List<long> idList)
    //{
    //    if (str == null)
    //        return;
    //    if (str == "")
    //        return;
    //    if (str == "-1")
    //        return;
    //    string[] nodeNames = str.Split('|');
    //    for (int i = 0; i < nodeNames.Length; ++i)
    //    {
    //        string[] data = nodeNames[i].Split('=');
    //        if (data.Length == 2)
    //            idList.Add(long.Parse(data[1]));
    //    }
    //}

    /// <summary>
    /// 字符串生成字符串字典
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    static public int InitSmartDic(Dictionary<string, string> dic, string strParam)
    {

        string strDic = "";
        try
        {
            if (strParam != "")
            {
                string[] nodeNames = strParam.Split('|');
                for (int i = 0; i < nodeNames.Length; ++i)
                {
                    if (nodeNames[i] == "")
                        continue;
                    string[] data = nodeNames[i].Split('=');
                    if (data.Length != 2)
                    {
                        throw new ExceptionDicFormatError("[" + strParam + "]第" + (i + 1) + "个参数格式不对");
                    }
                    else
                    {
                        strDic = data[0];
                        dic.Add(data[0], data[1]);
                    }
                }
            }
        }
        catch (ArgumentException e)
        {
            throw new ExceptionDicError(strDic + " 重复了      " + e.Message);
        }
        return -1;
    }

    /// <summary>
    /// 字符串以|分割转换成int列表
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>

    public static List<int> TranslateStringToIntList(string str)
    {
        List<int> data = new List<int>();
        if (str == null)
            return null;
        if (str == "")
            return null;
        string[] temp = str.Split('|');
        for (int i = 0; i < temp.Length; ++i)
        {
            data.Add(int.Parse(temp[i]));
            //Debug.Log(data[i]);
        }
        return data;
    }
    /// <summary>
    /// 字符串以_为间隔，转成字符串列表
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static List<string> TranslateStringToStringListByLine(string str, string splitParam = "-")
    {
        List<string> data = new List<string>();
        if (str == null)
            return null;
        if (str == "")
            return null;
        string[] temp = str.Split(splitParam.ToCharArray());
        for (int i = 0; i < temp.Length; ++i)
        {
            data.Add(temp[i]);
        }
        return data;
    }


    // 替换字符串中的关键字
    public static string ReplaceKeyOfString(string data)
    {
        if (string.IsNullOrEmpty(data))
            return "";


        //if(data.Contains("#player_name"))
        //{
        //    data =  data.Replace("#player_name", DataPlayer.Instance().m_strName);
        //}
        //if(data.Contains("#player_gender"))
        //{
        //    string it = DataPlayer.Instance().m_nSex == 0 ? LanguageManager.Instance().GetWord("player_gender_he") : LanguageManager.Instance().GetWord("player_gender_she");
        //    data = data.Replace("#player_gender", it);
        //}

        //Dictionary<string, GenderResData> m_dicGenderWords = LanguageManager.Instance().DicGenderWords;
        //foreach(var item in m_dicGenderWords){
        //    if(data.Contains(item.Key)){
        //        string str = DataPlayer.Instance().m_nSex == 0 ? item.Value.m_he : item.Value.m_she;
        //        data =  data.Replace(item.Key, LanguageManager.Instance().GetRealWord(str));
        //    }
        //}
        return data;
    }



    //public static Vector3 DampVector3(Vector3 toVector,Vector3 speed,float t)
    //{
    //    Vector3 end = Vector3.zero;
    //    float x, y, z;
    //    Mathf.SmoothDamp
    //    float speedX = speed.x;
    //    float speedY = speed.y;
    //    float speedZ = speed.z;
    //    return end;
    //}

    public static string ChangeNonBreakingSpaceText(string str)
    {
        if (string.IsNullOrEmpty(str))
            return "";
        string no_breaking_space = "\u00A0";
        if (str.Contains(" "))
            return str.Replace(" ", no_breaking_space);
        return str;
    }

    public static string SearchString(string s, string s1, string s2)
    {
        int n1, n2;
        n1 = s.IndexOf(s1, 0);
        if (n1 < 0)
        {
            return "";
        }
        n1 = n1 + s1.Length;
        n2 = s.IndexOf(s2, n1);
        return s.Substring(n1, n2 - n1);
    }
    // 浮点值按des保留有效数字
    // 这里先把小数保留位数计算好，转换成字符串，然后转换成浮点，会自动去掉无效的0，在转换成字符串，就成了指定位数的额有效数字
    public static string GetFloatDecimalString(float fValue, int dec)
    {
        string str = "#0.";
        for (int i = 0; i < dec; ++i)
            str += "0";
        return float.Parse(fValue.ToString(str)).ToString();
    }

    public static string StringFormatWithStrParam(string msg, string strParam)
    {
        string[] args = strParam.Split(',');
        string[] b = msg.Split('{');
        if (b.Length - 1 == args.Length)
            return string.Format(msg, args);
        return msg;
    }


    public static string NormalizeString(string str)
    {
        char space = (char)160;
        char newSpace = (char)32;
        return str.Replace(space, newSpace);
    }

    public static List<string> CreateStringList()
    {
        List<string> strList = new List<string>();

        return strList;
    }

    public static string ToMoneyNum(float num)
    {
        if (num > 9999)
        {
            return Mathf.Floor(num / 1000.0f) + "K";
        }
        return num.ToString();
    }

    public static string FormatTime(float t, int type = 0)
    {
        int d = Convert.ToInt16(t / 86400);
        float h = Convert.ToInt16((t % 86400) / 3600);
        float m = Convert.ToInt16((t % 86400 % 3600) / 60);
        float s = Convert.ToInt16(t % 86400 % 3600 % 60);

        string str = "";
        if (type == 0)//时分秒
        {
            str = h.ToString("00") + ":" + m.ToString("00") + ":" + s.ToString("00");
        }
        else if (type == 1)
        { //分秒
            if (h > 0)
            {
                str = h.ToString("00") + ":" + m.ToString("00") + ":" + s.ToString("00");
            }
            else
            {
                str = m.ToString("00") + ":" + s.ToString("00");
            }
        }
        else if (type == 1)
        { //秒
            if (h > 0)
            {
                str = h.ToString("00") + ":" + m.ToString("00") + ":" + s.ToString("00");
            }
            else if (m > 0)
            {
                str = m.ToString("00") + ":" + s.ToString("00");
            }
            else
            {
                str = s.ToString("00");
            }
        }
        return str;
    }
}
